package com.wxzz.elearning.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.wxzz.elearning.common.bean.SmsConfig;
import com.wxzz.elearning.common.bean.SpringContextUtils;
import com.wxzz.elearning.common.constants.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.Base64;

@Slf4j
@Component
public class SmsUtil {

    public static void main(String[] args) {
        SmsUtil smsUtil = new SmsUtil();
        ArrayList arrayList = new ArrayList();
        arrayList.add("啊啊啊");
        arrayList.add("2021-06-08");
        smsUtil.sendMsg("15057187652", SmsConfig.enterpriseCheckFailId, arrayList);
    }

    //直接从文档中拿取
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    public String buildRequestBody(String sender, String receiver, String templateId, String templateParas, String statusCallbackUrl, String signature) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            System.out.println("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }
        List<NameValuePair> keyValues = new ArrayList<NameValuePair>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }

    public String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            System.out.println("buildWsseHeader(): appKey or appSecret is null.");
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date()); //Created
        String nonce = UUID.randomUUID().toString().replace("-", ""); //Nonce

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes()); //PasswordDigest

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }


    /**
     * 通知类短信
     * @param receiver
     * @param templateId
     * @param params
     */
    public void sendMsg(String receiver, String templateId, List<String> params) {
        //史诗级天坑 如果用RedisTemplate<String,String> 获取出来的数据都是以前的数据
        StringRedisTemplate redisTemplate = (StringRedisTemplate)SpringContextUtils.getBean("stringRedisTemplate");
        String sender = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "sender");
        String signature = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "signature");
        String appKey = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "appKey");
        String appSecret = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "appSecret");
        String body = this.buildRequestBody(sender, receiver, templateId, JSONObject.toJSONString(params), SmsConfig.statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            log.error("发送消息接口调用错误[body is null.]");
            return;
        }
        String wsseHeader = this.buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            log.error("发送消息接口调用错误[wsse header is null.]");
            return;
        }
        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                    .setUri(SmsConfig.url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());

                System.out.println(response.toString()); //打印响应头域信息
            System.out.println(EntityUtils.toString(response.getEntity()));//打印响应消息实体
        } catch (Exception e) {
            log.error("发送消息接口调用错误[{}]", e.getMessage());
        }
    }

    /**
     * 验证码类短信
     * @param receiver
     * @param templateId
     * @param params
     */
    public void sendVerifyMsg(String receiver, String templateId, List<String> params) {
        //史诗级天坑 如果用RedisTemplate<String,String> 获取出来的数据都是以前的数据
        StringRedisTemplate redisTemplate = (StringRedisTemplate)SpringContextUtils.getBean("stringRedisTemplate");
        String verifySender = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "verifySender");
        String signature = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "signature");
        String appKey = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "appKey");
        String appSecret = redisTemplate.opsForValue().get(RedisConstants.SMS_PARAM + "appSecret");
        String body = this.buildRequestBody(verifySender, receiver, templateId, JSONObject.toJSONString(params), SmsConfig.statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            log.error("发送消息接口调用错误[body is null.]");
            return;
        }
        String wsseHeader = this.buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            log.error("发送消息接口调用错误[wsse header is null.]");
            return;
        }
        try {
            CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .build();

            HttpResponse response = client.execute(RequestBuilder.create("POST")//请求方法POST
                    .setUri(SmsConfig.url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());

            System.out.println(response.toString()); //打印响应头域信息
            System.out.println(EntityUtils.toString(response.getEntity()));//打印响应消息实体
        } catch (Exception e) {
            log.error("发送消息接口调用错误[{}]", e.getMessage());
        }
    }
}
